package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.dto.EmployeeListDto;
import cn.livingCloud.entity.core.Employee;
import cn.livingCloud.entity.core.EmployeeWechat;
import cn.livingCloud.entity.core.SelfBinding;
import cn.livingCloud.repository.EmployeeMapper;
import cn.livingCloud.repository.EmployeeWechatMapper;
import cn.livingCloud.repository.SelfBindingMapper;

import java.util.List;
import java.util.Objects;

/**
 * Created by DingJie on 2016/6/23.
 */
public class SelfBindingDtoCreator {

    private transient EmployeeWechatMapper employeeWechatMapper = BeanProvider.getBean(EmployeeWechatMapper.class);
    private transient EmployeeMapper employeeMapper = BeanProvider.getBean(EmployeeMapper.class);
    private transient SelfBindingMapper selfBindingMapper = BeanProvider.getBean(SelfBindingMapper.class);

    private String uuid;

    public SelfBindingDtoCreator(String uuid) {
        this.uuid = uuid;
    }

    public boolean create() {
        //查询不到return
        SelfBinding selfBinding = selfBindingMapper.selectByPrimaryKey(uuid);
        if (selfBinding == null) {
            return false;
        }
        //查询到多个 return
        List<Employee> list = getEmployees(selfBinding);
        if (list.isEmpty() || list.size() > 1) {
            return false;
        }
        //手机号码不一致,return
        Employee employee = list.get(0);
        String phone = selfBinding.getPhone();
        return Objects.equals(phone, employee.getPhone()) && createEmployeeMember(selfBinding, list);

    }

    private boolean createEmployeeMember(SelfBinding selfBinding, List<Employee> list) {
        EmployeeWechat employeeWechat = new EmployeeWechat();
        employeeWechat.setMemberUuid(selfBinding.getMemberUuid());
        employeeWechat.setEmployeeUuid(list.get(0).getUuid());
        employeeWechatMapper.insert(employeeWechat);
        //当前SelfBinding的Auditing审核状态修改为true
        selfBinding.setAuditing(true);
        selfBindingMapper.updateByPrimaryKey(selfBinding);
        return true;
    }

    private List<Employee> getEmployees(SelfBinding selfBinding) {
        EmployeeListDto employeeListDto = new EmployeeListDto();
        employeeListDto.setName(selfBinding.getEmployeeName());
        employeeListDto.setDept(selfBinding.getDeptName());
        return employeeMapper.getList(employeeListDto);
    }
}
